<template>
  <div>
    <div class="search-container">
      <el-input
        v-model="account"
        placeholder="账户"
        style="width: 15%; margin-right: 20px; margin-left: 20px; "
        class="rounded-input"
      />
      <el-input
        v-model="userName"
        placeholder="名称"
        style="width: 15%; margin-right: 20px;"
        class="rounded-input"
      />
      <el-select
        v-model="sex"
        placeholder="性别"
        style="width: 10%; margin-right: 20px;"
        class="rounded-input"
      >
        <el-option label="男" value="1"></el-option>
        <el-option label="女" value="0"></el-option>
      </el-select>
      <el-button
        type="text"
        icon="el-icon-search"
        @click="fetchData"
        style="margin-left: 0;"
      ></el-button>
      <el-button
        type="text"
        icon="el-icon-refresh"
        @click="resetSearch"
        style="margin-left: 10px;"
      ></el-button>
    </div>
    <el-table :data="paginatedData" style="width: 100%">
      <el-table-column prop="rowId" label="ID" width="100"></el-table-column>
      <el-table-column prop="avatar" label="头像" width="120">
        <template slot-scope="scope">
          <div class="image-container">
            <img :src="scope.row.avatar" alt="头像" class="record-image" />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="userName" label="名称" width="120"></el-table-column>
      <el-table-column prop="account" label="账户" width="120"></el-table-column>
      <el-table-column prop="sex" label="性别" width="100"></el-table-column>
      <el-table-column prop="role" label="角色" width="120"></el-table-column>
      <el-table-column prop="permission" label="权限" width="140"></el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="130"></el-table-column>
      <el-table-column prop="phone" label="电话" width="130"></el-table-column>
      <el-table-column prop="introduce" label="介绍" width="130"></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleUpdate(scope.$index, scope.row)">更新</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <div>
    <!-- ... 其他代码 -->
    <el-dialog title="详细信息" :visible.sync="dialogVisible" width="50%">
      <el-form :inline="true" label-width="100px">
        <el-form-item>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :http-request="updateUpload"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="dialogData.avatar" :src="dialogData.avatar" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-col>
            <el-col :span="16"  style="padding-left: 50px">
              <el-form-item label="名称">
                <el-input v-model="dialogData.userName" style="font-size: 16px;"></el-input>
              </el-form-item>
              <el-form-item label="账户">
                <el-input v-model="dialogData.account" style="font-size: 16px;"></el-input>
              </el-form-item>
              <el-form-item label="性别" >
                <el-radio-group v-model="dialogData.sex">
                  <el-radio label="1">男</el-radio>
                  <el-radio label="0">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="状态">
                <el-switch
                  v-model="dialogData.status"
                  :active-value="0"
                  :inactive-value="1"
                  style="font-size: 16px;"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row :gutter="20">
            <el-col :span="13">
              <el-form-item label="邮箱">
                <el-input v-model="dialogData.email" style="font-size: 16px;"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="电话">
                <el-input v-model="dialogData.phone" style="font-size: 16px;"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row :gutter="20">
            <el-col :span="13">
              <el-form-item label="角色">
                <el-input v-model="dialogData.role" style="font-size: 16px;" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="权限">
                <el-input v-model="dialogData.permission" style="font-size: 16px;" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="简介" label-width="100px" label-position="top">
          <el-input
            type="textarea"
            v-model="dialogData.introduce"
            :rows="4"
            style="font-size: 16px;"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>
    </div>
  </div>
</template>

<script>
import { selectPage, updateStatus, getInfoById, updateInfo, deleteById, upload } from '@/api/user';

export default {
  name: 'User',
  data() {
    return {
      tableData: [], // 假设这是从API获取的数据
      currentPage: 1,
      pageSize: 10,
      total: 0,
      userName: null,
      account: null,
      sex: null,
      dialogData: {},
      dialogVisible: false
    };
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tableData.slice(start, end).map((row,index) => ({
        ...row,
        rowId: start + index + 1,
        sex: row.sex == 1 ? '男' : '女'
      }))
    },
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      const params ={
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        userName: this.userName,
        account: this.account,
        sex: this.sex != null ? Number(this.sex) : null
      };

      // 这是一个获取数据的API调用
      selectPage(params)
        .then(response => {
          this.tableData = response.data.result;
          this.total = response.data.total;
        })
        .catch(error => {
          console.error('获取数据失败', error);
          this.$message({
            message: response.message,
            type: 'error'
          });
        });
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },

    handleUpdate(index, row) {
      // 实现更新逻辑
      console.log('更新回显', index, row);
      getInfoById(row.id)
        .then(response => {
          this.dialogData = response.data; // 将返回的数据存储到dialogData
          this.dialogVisible = true; // 显示对话框
        })
        .catch(error => {
          console.error('获取用户信息失败', error);
          this.$message({
            message: response.message,
            type: 'error'
          });
        });
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 实现删除逻辑
        console.log('删除', index, row);
        deleteById(row.id).then(response => {
          console.log(response)
          console.log('删除成功', response);
          if(response.code === 200){
            this.$message({
              message: "删除成功!",
              type: 'success'
            });
          }else{
            this.$message({
              message: response.message,
              type: 'error'
            });
          }
          this.fetchData(); // 重新获取数据
        }).catch(error => {
          console.error('删除失败', error);
        });
      }).catch(() => {
         // 用户点击取消
        this.$message({
          message: '已取消删除~',
          type: 'info'
        });
      })
    }, 
    handleStatusChange(row) {
      const newStatus = row.status;
      const params = {
        id: row.id,
        status: newStatus
      };

      // 调用更新状态的API
      updateStatus(params)
        .then(response => {
          if(response.code == 200){
              this.$message({
              message: '状态更新成功！',
              type: 'success'
            });
          }else{
              this.$message({
              message: response.message,
              type: 'error'
            });
          }
          // 如果需要，可以在这里重新获取数据
          this.fetchData();
        })
        .catch(error => {
          console.error('状态更新失败！', error);
          // 恢复到原来的值
          row.status = newStatus === 0 ? 1 : 0;
        });
    },
    resetSearch() {
      // 清空搜索框中的所有输入并恢复默认选项
      this.userName = null;
      this.account = null;
      this.sex = null;
      this.fetchData(); // 重新获取数据
    },
    updateUser() {
      console.log('更新用户信息', this.dialogData);
      // 你可以在这里调用更新API
      // 提取必要的字段
      const updateParams = {
        id: this.dialogData.id,
        avatar: this.dialogData.avatar,
        userName: this.dialogData.userName,
        account: this.dialogData.account,
        sex: this.dialogData.sex,
        status: this.dialogData.status,
        email: this.dialogData.email,
        phone: this.dialogData.phone,
        introduce: this.dialogData.introduce
      };

      updateInfo(updateParams).then(response => {
        console.log('更新成功', response);
        if(response.code == 200){
          this.$message({
            message: '更新成功！',
            type: 'success'
          });
        }else{
          this.$message({
            message: response.data,
            type: 'error'
          });
        }
        this.dialogVisible = false; // 关闭对话框
        this.fetchData(); // 重新获取数据
      }).catch(error => {
        console.error('更新失败', error);
      });
    },
    handleAvatarSuccess(res, file) {
      this.dialogData.avatar = URL.createObjectURL(file.raw);
    },

    updateUpload(options) {
      const { file } = options;
      const bucket = 'pest-control';             // 固定 bucket
      const objectName = 'image';                // 固定目录名

      upload(file, bucket, objectName)
        .then(response => {
          if (response.code === 200 && response.data) {
            this.dialogData.avatar = response.data; // 接收返回的 URL
            this.$message.success('上传成功');
          } else {
            this.$message.error('上传失败：' + (response.message || '未知错误'));
          }
        })
        .catch(() => {
          this.$message.error('请求出错，请重试');
        });
    },
    
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }

  },
};
</script>

<style scoped>
.search-container {
  margin-bottom: 20px;
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.rounded-input .el-input__inner {
  border-radius: 20px;
  width: 15%;
  margin-right: 10px;
}


.rounded-input:last-child .el-input__inner {
  border-radius: 20px;
  margin-right: 10px;
}

.el-select .el-input__inner {
  border-radius: 20px;
  width: 15%;
  margin-right: 10px;
}

.el-button--text {
  padding: 0; /* 去掉按钮的内边距 */
  margin-left: 10px; /* 调整按钮的左边距 */
  font-size: 20px;
}


.monitor-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh; /* 确保容器至少占满整个视口高度 */
  padding: 20px;
  box-sizing: border-box;
}

.monitor-table {
  width: 100%;
  flex: 1; /* 使表格内容占据剩余空间 */
  margin-bottom: 20px;
}

.record-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
}

.pagination-container {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 20px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff; /* 确保背景颜色与页面一致 */
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  padding: 10px;
  box-sizing: border-box;
}

.el-table {
  margin-bottom: 60px; /* 根据分页组件的高度调整这个值 */
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  height: 178px;
  display: flex;
  justify-content: flex-start; /* 左对齐 */
  align-items: center;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  margin-left: 60px;
  margin-right: 50px;
}

.el-form-item {
  display: flex;
  align-items: center; /* 垂直居中 */
  margin-bottom: 10px; /* 表单项之间的间距 */
}

.el-form-item__label {
  flex-shrink: 0; /* 防止 label 被压缩 */
  width: 100px; /* 固定 label 宽度 */
}

.el-input__inner {
  font-size: 16px;
}

.el-select .el-input__inner {
  font-size: 16px;
}

.el-textarea__inner {
  font-size: 16px;
}

.el-row {
  margin-bottom: 10px;
}

.el-col {
  padding-right: 10px;
}

.el-form-item--small.el-form-item {
  margin-bottom: 10px;
}

.el-form-item .el-form-item__content {
  flex-grow: 1; /* 输入框占据剩余空间 */
}


</style>